package com.example.demo.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.example.demo.entity.Files;
import com.example.demo.mapper.FileMapper;
import com.example.demo.service.IFileService;
import com.example.demo.service.PersonService;
import com.example.demo.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author king
 * @since 2024-04-14
 */
@RestController
@RequestMapping("/file")
@CrossOrigin  //解决跨域
@Api( tags = "file接口")
public class FileController {
    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Value("${rdsWebUrl.rdsUrl}")
    private String localurl;
    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private IFileService fileService;
    @Autowired
    private PersonService personService;
    /*
    /  文件上传接口
     */
    @ApiOperation("导入文件信息")
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originFilename=file.getOriginalFilename();
        String type= FileUtil.extName(originFilename);
        Long size=file.getSize();

        //定义文件唯一的标识码

        String uuid= IdUtil.fastSimpleUUID();
        String fileuuid=uuid+ StrUtil.DOT+type;
        File uploadFile=new File(fileUploadPath+fileuuid);

        //判断配置的文件目录是否存在 如果不存在就创建一个新的文件目录
        if(!uploadFile.getParentFile().exists())
        {
            uploadFile.getParentFile().mkdir();
        }
        //当文件存在的时候在获取文件的md5

        String url;
        String md5;

            //把获取的到文件存到磁盘目录
            file.transferTo(uploadFile);
            //获取文件的md5
            //通过文件获取MD5 对比避免重复上传一些文件
             md5= SecureUtil.md5(uploadFile);
            List<Files> dbFiles=getFilesByName(md5);
            if(dbFiles!=null)
            {
                url=dbFiles.get(0).getUrl();

                uploadFile.delete();
            }
            else
            {
                //把获取的到文件存到磁盘目录
//                file.transferTo(uploadFile);
                url=localurl+"/file/"+fileuuid;
            }


        //存储数据库
        Files saveFile=new Files();
        saveFile.setName(originFilename);
        saveFile.setType(type);
        saveFile.setSize(size/1024);
        saveFile.setUrl(url);
        saveFile.setMd5(md5);
        saveFile.setIsDelete(false);
        saveFile.setEnable(false);
         fileMapper.insert(saveFile);



         return url ;
    }
    @ApiOperation("批量导入文件信息")
    @PostMapping("/uploadList")
    public Result uploadList(@RequestParam List<MultipartFile> files) throws IOException {
        Result result=new Result<>();
        for(MultipartFile file:files) {
            String originFilename = file.getOriginalFilename();
            String type = FileUtil.extName(originFilename);
            Long size = file.getSize();

            //定义文件唯一的标识码

            String uuid = IdUtil.fastSimpleUUID();
            String fileuuid = uuid + StrUtil.DOT + type;
            File uploadFile = new File(fileUploadPath + fileuuid);

            //判断配置的文件目录是否存在 如果不存在就创建一个新的文件目录
            if (!uploadFile.getParentFile().exists()) {
                uploadFile.getParentFile().mkdir();
            }
            //当文件存在的时候在获取文件的md5

            String url;
            String md5;

            //把获取的到文件存到磁盘目录
            file.transferTo(uploadFile);
            //获取文件的md5
            //通过文件获取MD5 对比避免重复上传一些文件
            md5 = SecureUtil.md5(uploadFile);
            List<Files> dbFiles = getFilesByName(md5);
            if (dbFiles != null) {
                url = dbFiles.get(0).getUrl();

                uploadFile.delete();
            } else {
                //把获取的到文件存到磁盘目录
//                file.transferTo(uploadFile);
                url=localurl+"/file/"+fileuuid;
            }


            //存储数据库
            Files saveFile = new Files();
            saveFile.setName(originFilename);
            saveFile.setType(type);
            saveFile.setSize(size / 1024);
            saveFile.setUrl(url);
            saveFile.setMd5(md5);
            saveFile.setIsDelete(false);
            saveFile.setEnable(false);
           int p= fileMapper.insert(saveFile);
           if(p==1)
           {

           }
           else
           {
               result.setMessage("有文件没有导入成功");
               return result;
           }
        }


        result.setMessage("全部导入成功");
        return result;
    }
/*
* 文件下载路径
*   String url="http://localhost:8181/file/"+fileuuid;
* */
@ApiOperation("下载当前文件信息")
    @GetMapping("/{fileuuid}")
    public void download(@PathVariable String fileuuid, HttpServletResponse response) throws IOException {
        //根据文件唯一的标识码获取文件
        File uploadFile=new File(fileUploadPath+fileuuid);
        ServletOutputStream os=response.getOutputStream();
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileuuid,"UTF-8"));
        response.setContentType("application/octet-stream");
        //读取文件字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }
    public List<Files> getFilesByName(String md5)
    {
        //判断当前这个md5是否已经存在了
        LambdaQueryWrapper<Files>filesLambdaQueryWrapper=new LambdaQueryWrapper<>();
        filesLambdaQueryWrapper.eq(Files::getMd5,md5);
        List<Files> files=fileMapper.selectList(filesLambdaQueryWrapper);
        return files.size()==0?null:files;
    }
    @ApiOperation("获取当前文件信息")
    @GetMapping("/page")
    public Result page(@RequestParam Integer pageNo
            , @RequestParam Integer pageSize
            , @RequestParam(defaultValue = "") String  name)
           {
//        方法1：
//        pageNo=(pageNo - 1)*pageSize;
////        System.out.println(pageNo);
//        Map<String ,Object> res =new HashMap<>();
////        System.out.println(params);
////        System.out.println(pageSize+"");
////        System.out.println(pageNo);
//        Integer total=usermapper.selectTotal();
//        userName='%'+userName+'%';
//        email='%'+email+'%';
//        address='%'+address+'%';
////        System.out.println(total);
//        List<User>data=usermapper.selectPage(pageNo, pageSize,userName,email,address);
        Result result=new Result<>();
        IPage<Files> page=new Page<>(pageNo,pageSize);
        QueryWrapper<Files> filesQueryWrapper=new QueryWrapper<>();
               filesQueryWrapper.in("name", new String[]{name + ".doc",name + ".docx",name + ".pdf"});
               //查询未被删除的文件
               filesQueryWrapper.eq("is_delete",false);
//        userQueryWrapper.like("email",email);
//        userQueryWrapper.like("address",address);
               filesQueryWrapper.orderByDesc("id");
//        res.put("data",data);
//        res.put("total",total);
//        result.setData(res);
//        System.out.println(res);
               if(fileService.page(page,filesQueryWrapper).getRecords().size()==0)
               {

                           IPage<Files> page1=new Page<>(pageNo,pageSize);
                           QueryWrapper<Files> filesQueryWrapper1=new QueryWrapper<>();
                           filesQueryWrapper1.like("name",name);
                           //查询未被删除的文件
                           filesQueryWrapper1.eq("is_delete",false);
                           filesQueryWrapper1.orderByAsc("name");
                           String message="";
                           message+="";
                           List<Files>list=fileService.page(page,filesQueryWrapper1).getRecords();
                           if(list!=null&&list.size()!=0)
                           {
                               result.setResult(list);
                               message+="找到以下和《"+name+"》相关的期刊模板：";
                               result.setMessage(message);
                               return result;
                           }
                   else
                   {
                       result.setMessage("未找到和《"+name+"》相关的内容。");
                       result.setResult( fileService.page(page,filesQueryWrapper).getRecords());
                       return result;
                   }
               }


               else
               {
                   result.setMessage("已拿到数据");
                   result.setResult( fileService.page(page,filesQueryWrapper).getRecords() );
                   return result;
               }
    }

    @GetMapping("/delete")
    @ApiOperation(value = "逻辑删除文件信息")
    public Result deleteById(@RequestParam String id)
    {
        Result result=new Result<>();
        Files files=fileMapper.selectById(id);
        files.setIsDelete(true);
        int p=fileMapper.updateById(files);
        result.setResult(p);
        return result;
    }
    @PostMapping("/deleteAll")
    @ApiOperation(value = "删除一群文件信息")
    public Result deleteAll(@RequestBody List<String> ids)
    {
        Result result=new Result<>();
        List<Files> files=fileMapper.selectBatchIds(ids);
        for(Files files1:files)
        {
            files1.setIsDelete(true);
        }
        result.setResult(fileService.updateBatchById(files));
        return result;
    }
    @PostMapping("/update")
    @ApiOperation("修改文件信息")
    public boolean update(@RequestBody Files files)
    {
        System.out.println(files);
        QueryWrapper<Files>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",files.getId());
        return fileService.update(files,queryWrapper);
    }
}

